<?php


namespace app\admin\service;


use app\common\Log;
use app\common\OutPay\SafePay;
use app\utility\HttpHelper;

/**
 * 兑换
 * Class PayService
 * @package App\Admin\Services
 */
class OutPayService
{

    const URL = '/web/exchange_union_score';

    /**
     * 异步提交代付订单
     */
    public static function submit()
    {
        $list = ExchangeListModel::query()->where('status', ExchangeListModel::STATUS_ONLINE)->get();

        $appId = ConfigService::appId() ?: 1000;
        $exchange = ChannelModel::query()->where('id', $appId)->value('exchange_info');
        $exchange = $exchange[0];

        if (!$list || !$exchange) {
            return;
        }
        /** @var ExchangeListModel $item */
        foreach ($list as $item) {
            switch ($exchange) {
                case 4:
                case 6:
                    $outPay = new SafePay(config('outpay.safe_pay'));
                    break;
                default:
                    return;
            }
            $item->third_id = $exchange;
            $is = $outPay->pay($item);
            if (!$is) {
                $item->remark = $outPay->getErr();
//                $item->status = ExchangeListModel::STATUS_INIT;
            } else {
                $item->status = ExchangeListModel::STATUS_PLAYING;
            }

            $item->save();
        }
    }


    public static function NotifyWebServer($data)
    {

        $ret = HttpHelper::post(config('custom.server_url') . self::URL, json_encode($data));
        $ret = json_decode($ret, true);
        if ($ret['ReturnCode'] == 0) {
            ExchangeListModel::query()->where('order_no', $data['order_id'])->update(['finish_time' => time(), 'status' => ExchangeListModel::STATUS_FINISH]);
            return true;

        } else {
            Log::write('通知服务器失败：' . json_encode($ret) . '，订单号：' . $data['order_id'], 'outpay', 'outpay');
            return false;

        }

    }


    public static function NotifyWebServerError($data)
    {


            ExchangeListModel::query()->where('order_no', $data['order_id'])->update(['finish_time' => time(), 'status' => ExchangeListModel::STATUS_NO_EXCHANGE]);
            return true;


    }
    /**
     * 打款成功
     * @param ExchangeListModel $order
     * @param string $err
     * @return bool
     */
    public static function success(ExchangeListModel $order, &$err = '')
    {
        BaseModel::transaction();
        try {
            $now = time();
//            $order->status = ExchangeListModel::STATUS_FINISH;
//            $order->finish_time = $now;
//            $order->saveOrFail();

            $exchange = ExchangeListModel::query()->where('order_no', $order->order_no)->first();
            if (!($exchange instanceof ExchangeListModel)) {
                throw new \Exception('订单号找不到');
            }
            $exchange->status = ExchangeListModel::STATUS_FINISH;
            $exchange->finish_time = $now;
            $exchange->saveOrFail();

            //发送邮件
//            MailService::send(14, $exchange->user_id, $exchange->league_id);
            BaseModel::commit();
            return true;
        } catch (\Exception $e) {
            $err = $e->getMessage();
            BaseModel::rollBack();
        } catch (\Throwable $e) {
            $err = $e->getMessage();
            BaseModel::rollBack();
        }
        return false;
    }

    /**
     * 打款失败
     * @param ExchangeListModel $order
     * @param string $err
     * @return bool
     */
    public static function error(ExchangeListModel $order, &$err = '')
    {
        BaseModel::transaction();
        try {
            $now = time();
            $order->status = ExchangeListModel::STATUS_OFFLINE;
            $order->finish_time = $now;
            $order->saveOrFail();

            $exchange = ExchangeListModel::query()->where('order_no', $order->order_no)->first();
            if (!($exchange instanceof ExchangeListModel)) {
                throw new \Exception('订单号找不到');
            }
            $exchange->status = ExchangeListModel::STATUS_NO_EXCHANGE;//兑换失败
            $exchange->finish_time = $now;
            $exchange->saveOrFail();

            //加回积分
            $ret = AccountService::editScore($exchange->user_id, $exchange->guild_id, $exchange->score, 15);
            if ($ret !== true) {
                throw new \Exception($ret);
            }

            BaseModel::commit();
//            ConfigService::clearScore($exchange->user_id, $order->app_id);
            return true;
        } catch (\Exception $e) {
            $err = $e->getMessage();
            BaseModel::rollBack();
        } catch (\Throwable $e) {
            $err = $e->getMessage();
            BaseModel::rollBack();
        }
        return false;
    }
}